package cn.wp.ewallet.common.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.wp.common.core.authentication.AuthenticationContext;
import cn.wp.common.core.dto.WpResult;
import cn.wp.common.core.id.Id;
import cn.wp.common.core.util.BeanUtil;
import cn.wp.ewallet.common.extension.constant.EwalletConstant;
import cn.wp.ewallet.common.model.dto.ConverRuleDictDto;
import cn.wp.ewallet.common.service.ConverRoleDictService;
import cn.wp.ewallet.common.dao.ConverRoleDictDao;
import cn.wp.ewallet.common.model.entity.ConverRuleDictDo;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by yangjin on 2020/1/13
 */
@Service
public class ConverRoleDictServiceImpl implements ConverRoleDictService {

    @Autowired
    private ConverRoleDictDao converRoleDictDao;

    @Autowired
    private AuthenticationContext authenticationContext;

    @Override
    public WpResult exchangeMoneyRatioSetting(String params) {
        List<ConverRuleDictDto> objects = JSONObject.parseArray(params, ConverRuleDictDto.class);

        if (CollectionUtil.isEmpty(objects)) {
            return new WpResult().failure();
        }

        for (ConverRuleDictDto obj : objects) {
            ConverRuleDictDo converRuleDictDo = converRoleDictDao.selectConverRuleDict(obj.getBaseMoney(),obj.getPriceMoney(),obj.getConverType());
            if(null != converRuleDictDo) {
                converRuleDictDo.setStatus(EwalletConstant.INVALID_STATUS);
                converRoleDictDao.updateConverRuleDict(converRuleDictDo);
            }
            ConverRuleDictDo converRuleDict = new ConverRuleDictDo();
            converRuleDict.setRuleId(Id.gen());
            converRuleDict.setBaseMoney(obj.getBaseMoney());
            converRuleDict.setConverType(obj.getConverType());
            converRuleDict.setPriceMoney(obj.getPriceMoney());
            converRuleDict.setExchangeRate(obj.getExchangeRate());
            converRuleDict.setStatus(EwalletConstant.STATUS);
            converRuleDict.setStatusTime(new Date());
            converRuleDict.setOperUser(authenticationContext.currentUser().getId());
            converRoleDictDao.insertConverRuleDict(converRuleDict);
        }

        return new WpResult().success();
    }

    @Override
    public ConverRuleDictDto getConverRuleDict(String baseMoney, String priceMoney, String converType) {
        return BeanUtil.copyProperties(converRoleDictDao.selectConverRuleDict(baseMoney, priceMoney, converType), ConverRuleDictDto.class);
    }

    @Override
    public List<ConverRuleDictDto> getExchangeMoneyRatio() {
        return BeanUtil.listCopyProperties(converRoleDictDao.selectConverRuleDict(), ConverRuleDictDto.class);
    }

}
